package pl.register.android.database.crud;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import pl.register.android.course.Course;
import pl.register.android.database.tables.StudentClassNumberDBTable;
import pl.register.android.student.Student;

/**
 * @author Mateusz Strzelecki
 * @since 2013-04-27
 */
public class StudentClassNumberCRUD {

    private SQLiteDatabase database;

    public StudentClassNumberCRUD(SQLiteDatabase database) {
        this.database = database;
    }

    public void insert(Student student, Course course) {
        ContentValues insertValues = new ContentValues();
        insertValues.put(StudentClassNumberDBTable.CLASS_NUMBER, student.getClassNo());
        insertValues.put(StudentClassNumberDBTable.FK_COURSE_ID, course.getId());
        insertValues.put(StudentClassNumberDBTable.FK_STUDENT_ID, student.getId());
        long idRow = database.insert(StudentClassNumberDBTable.TABLE_NAME, null, insertValues);
    }

    public void update(Student student, Course course) {
        String where = StudentClassNumberDBTable.FK_STUDENT_ID + " = " + student.getId()
                + " AND " +
                StudentClassNumberDBTable.FK_COURSE_ID + " = " + course.getId();
        ContentValues updateValues = new ContentValues();
        updateValues.put(StudentClassNumberDBTable.CLASS_NUMBER, student.getClassNo());
        long rowId = database.update(StudentClassNumberDBTable.TABLE_NAME, updateValues, where, null);
    }

    public String findClassNumber(Student student, Course course) {
        String classNumber = "";
        String where = StudentClassNumberDBTable.FK_STUDENT_ID + " = " + student.getId()
                + " AND " +
                StudentClassNumberDBTable.FK_COURSE_ID + " = " + course.getId();
        Cursor cursor = database.query(StudentClassNumberDBTable.TABLE_NAME, null, where, null, null, null, null);
        if (cursor.moveToFirst()) {
            classNumber = cursor.getString(cursor.getColumnIndex(StudentClassNumberDBTable.CLASS_NUMBER));
        }
        cursor.close();
        return classNumber;
    }

}
